package Dao;

import POJO.Weather;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.stream.*;
public class WeatherInfoGet {
    private static final String INSERT_STUDENT_SQL = "INSERT INTO weather_info (id,weather_data) VALUES (?, ?)";
    private static final String delete_STUDENT_SQL = "DELETE FROM weather_info";


    public static void main(String[] args) throws IOException {
        String apiKey = "S46LDdzxlR22Ar_nG"; // 替换为你的心知天气API密钥
//        String location = "wuhan";
        //创建一个天气列表包含各种城市
        String[] locations = {"wuhan", "beijing", "shanghai", "guangzhou",
                "shenzhen", "hangzhou", "nanjing", "chengdu", "chongqing",
                "xian", "tianjin", "shijiazhuang", "qingdao", "haerbin", "shenyang",
                "changchun", "jilin", "haikou", "foshan", "zhuhai", "guilin", "nanning", "lanz"};
        //选择其中的一个作为测试
        String language = "zh-Hans";
        String unit = "c";
     //   deleteWeather();//-----------------------------
        for (String location : locations) {
            String urlString = "https://api.seniverse.com/v3/weather/now.json?key=" +
                    apiKey + "&location=" + location + "&language=" + language + "&unit=" + unit;
            URL url = new URL(urlString);

            //写出get set方法

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }

                // Close the streams
                in.close();
                connection.disconnect();

                // Parse the JSON response
                JSONObject jsonObject = new JSONObject(content.toString());
                System.out.println(jsonObject);// 打印整个json

                JSONArray results = jsonObject.getJSONArray("results");
                System.out.println(results);

                JSONObject now = results.getJSONObject(0).getJSONObject("now");
                System.out.println(now);

                JSONObject location2 = results.getJSONObject(0).getJSONObject("location");
                System.out.println(location2);
                System.out.println(location2.getString("name"));


                // Extract relevant information and store in an array
                String[] weatherInfo1 = {
                        "城市: " + location2.getString("name"),
                        "温度: " + now.getString("temperature"),
                        "状况: " + now.getString("code"),
                        "天气: " + now.getString("text"),

                };

               Weather weather = new Weather(now.getInt("code"),location2.getString("name")+now.getString("text"));



//                System.out.println(weatherInfo.getId());
//                System.out.println(weatherInfo.getInfo());
//
//                System.out.println(weatherInfo);
                System.out.println(weather);

               insertWeather(weather);

                // Print the array
                for (String info : weatherInfo1) {
                    System.out.println(info);
                }
            } else {
                System.out.println("GET request not worked. Response Code: " + responseCode);
            }




        }


    }

    public static void insertWeather(Weather weather) {

        try (
                //  weatherDao.deleteWeather();------------这里面的方法在try---在里面和----在外面有什么区别
                Connection connection = DatabaseConnection.getConnection();
                PreparedStatement preparedStatement = connection.prepareStatement(INSERT_STUDENT_SQL)) {
            preparedStatement.setInt(1, weather.getId());
            preparedStatement.setString(2, weather.getWeatherData());
            int rowinserted = preparedStatement.executeUpdate();
            if (rowinserted > 0) {
                System.out.println("插入天气数据成功");}
            else {
                System.out.println("未找到指定的学生记录");
            }
        } catch (SQLException e) {

            e.printStackTrace();
        }
    }
    private static void deleteWeather() {

        try (
                //  weatherDao.deleteWeather();------------这里面的方法在try---在里面和----在外面有什么区别
                Connection connection = DatabaseConnection.getConnection();
                PreparedStatement preparedStatement = connection.prepareStatement(delete_STUDENT_SQL)) {

            int rowinserted = preparedStatement.executeUpdate();
            if (rowinserted > 0) {
                System.out.println("删除天气数据表成功");}
            else {
                System.out.println("删除失败");
            }
        } catch (SQLException e) {

            e.printStackTrace();
        }
    }


}
